//
//  VideoView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/3.
//

import SwiftUI

import SwiftUI
import AVKit

//视频播放，支持本地跟网络
struct MyVideoView: View {
    let url: URL
    @State private var player: AVPlayer?
    @State private var observer: NSObjectProtocol?
    @State private var isPlaying = false // 控制播放状态的变量
    
    var body: some View {
        Group {
            if let player = player {
                VideoPlayer(player: player)
                    .overlay(
                        ZStack {
                            // 透明交互层（统一处理点击事件）
                            Color.clear
                                .background(.white.opacity(0.0001)) //防止系统自带的点击
                                .frame(maxWidth: .infinity, maxHeight: .infinity)
                                .contentShape(Rectangle())
                                .onTapGesture {
                                    togglePlayPause()
                                }
                            // 自定义播放/暂停按钮
                            Image(systemName: "play.circle.fill")
                                .resizable()
                                .frame(width: 40, height: 40)
                                .foregroundColor(.white.opacity(0.8))
                                .opacity(isPlaying ? 0 : 1)
                        }
                    )
                    .onAppear {
                        setupAudioSession()
                        startPlayback()
                    }
                    .onDisappear {
                        pausePlayback()
                    }
            } else {
                ProgressView()
            }
        }
        .onAppear { setupPlayer() }
        .onDisappear { cleanUp() }
    }
}

// MARK: - 播放控制逻辑
extension MyVideoView {
    private func togglePlayPause() {
        isPlaying.toggle()
        isPlaying ? player?.play() : player?.pause()
    }
    
    private func startPlayback() {
        player?.play()
        isPlaying = true
    }
    
    private func pausePlayback() {
        player?.pause()
        isPlaying = false
    }
}

// MARK: - 播放器生命周期管理
extension MyVideoView {
    private func setupPlayer() {
        cleanUp()
        url.startAccessingSecurityScopedResource() //需要启用安全作用域访问，不然本地的无法播放
        let newPlayer = AVPlayer(url: url)
        player = newPlayer
        
        // 添加循环播放监听
        observer = NotificationCenter.default.addObserver(
            forName: .AVPlayerItemDidPlayToEndTime,
            object: newPlayer.currentItem,
            queue: .main
        ) { [weak newPlayer] _ in
            newPlayer?.seek(to: .zero)
            newPlayer?.play()
            isPlaying = true // 保持播放状态同步
        }
    }
    
    private func setupAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            showLog("Audio session setup failed: \(error)")
        }
    }
    
    private func cleanUp() {
        removeObserver()
        player?.pause()
        player = nil
    }
    
    private func removeObserver() {
        guard let observer = observer else { return }
        NotificationCenter.default.removeObserver(observer)
        self.observer = nil
    }
}
